package org.allen.framework.cloudatomiclock.aspect;

import lombok.extern.slf4j.Slf4j;
import org.allen.framework.cloudatomiclock.IAtomicLock;
import org.allen.framework.cloudatomiclock.annotation.NeedAtomicLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @Author: Allen
 * @Date: Created in 10:54 2019-10-11
 * @Description:
 */
@Aspect
@Slf4j
@Component
public class AtomicLockAspect {

    private IAtomicLock atomicLock;

    public AtomicLockAspect(IAtomicLock atomicLock) {
        this.atomicLock = atomicLock;
    }

    @Around("@annotation(org.allen.framework.cloudatomiclock.annotation.NeedAtomicLock)")
    public Object handle(ProceedingJoinPoint proceedingJoinPoint) {
        log.debug("分布式锁。。。start,method[{}]" ,proceedingJoinPoint.getTarget());
        Object proceed = null;
        try {
            NeedAtomicLock needAtomicLock = ((MethodSignature)proceedingJoinPoint.getSignature()).getMethod().getAnnotation(NeedAtomicLock.class);
            //上锁
            atomicLock.lock(needAtomicLock.value());
            proceed = proceedingJoinPoint.proceed();
            //解锁
            atomicLock.unlock(needAtomicLock.value());
            log.debug("分布式锁。。。end");
            return proceed;
        } catch (Throwable throwable) {
            log.error(throwable.getMessage() ,throwable);
            return null;
        }

    }

}
